package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.util.SMSUtils;
import com.itheima.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired
    private JedisPool jedisPool;
    @RequestMapping("/send4EditPwd")
    public Result send4send4EditPwd(String telephone){
        Jedis resource = jedisPool.getResource();
        //获取验证码
        Integer validateCode = null;
        try {
            validateCode = getValidateCode(telephone);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //将验证码保存到redis
        resource.setex(telephone + RedisMessageConstant.SENDTYPE_EDITPWD,300,validateCode.toString());
        resource.close();
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    //生成6位验证码
    public Integer getValidateCode(String telephone)throws Exception{
        //随机生成6位数验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(6);
        //给用户发送验证码
        SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, validateCode.toString());
        return validateCode;
    }
}
